package com.jz.community.moduleexpress.express;

import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.View;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.jz.community.basecomm.base.BaseMvpFragment;
import com.jz.community.basecomm.mvp.BaseMvpPresenter;
import com.jz.community.basecomm.task.ITaskCallbackListener;
import com.jz.community.basecomm.utils.BaseSpUtils;
import com.jz.community.basecomm.utils.RxDataTool;
import com.jz.community.basecomm.utils.WpToast;
import com.jz.community.moduleexpress.R;
import com.jz.community.moduleexpress.R2;
import com.jz.community.moduleexpress.express.adapter.ExpressInfoListAdapter;
import com.jz.community.moduleexpress.express.info.ExpressInfoBean;
import com.jz.community.moduleexpress.express.info.baseInfo.BaseEntity;
import com.jz.community.moduleexpress.express.task.GetExpressListTask;
import com.jz.community.moduleexpress.express.task.GetExpressSignTask;
import com.jz.community.moduleexpress.express.ui.PackageDetailActivity;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.listener.OnRefreshListener;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;

/**
 * Created by Tony.Fan on 2018/7/26 14:46
 */
public class UnclaimedPackageFragment extends BaseMvpFragment implements OnRefreshListener, BaseQuickAdapter.RequestLoadMoreListener {

    @BindView(R2.id.unclaimed_package_rv)
    RecyclerView unclaimedPackageRv;
    @BindView(R2.id.unclaimed_package_refresh)
    SmartRefreshLayout unclaimedPackageRefresh;
    private int expressType;
    private int page = 1;
    private int rows = 20;
    private ExpressInfoListAdapter expressInfoListAdapter;
    private List<ExpressInfoBean> expressInfoBeans;

    public static UnclaimedPackageFragment newInstance(int statue) {
        UnclaimedPackageFragment unclaimedPackageFragment = new UnclaimedPackageFragment();
        Bundle bundle = new Bundle();
        bundle.putInt("expressType", statue);
        unclaimedPackageFragment.setArguments(bundle);
        return unclaimedPackageFragment;
    }

    @Override
    protected void initDatas() {
        super.initDatas();
        bindExpressAdapter();
    }

    @Override
    protected void initLazy(@Nullable Bundle savedInstanceState) {
        super.initLazy(savedInstanceState);
        Bundle bundle = getArguments();
        expressType = bundle.getInt("expressType");
        loadExpressData();
    }

    @Override
    public void onLoadMoreRequested() {
        final int size = expressInfoBeans == null ? 0 : expressInfoBeans.size();
        if (size < rows) {
            expressInfoListAdapter.loadMoreEnd();
            unclaimedPackageRefresh.setEnableRefresh(true);
        } else {
            page++;
            loadExpressData();
            unclaimedPackageRefresh.setEnableRefresh(true);
        }
    }

    @Override
    protected int getContentViewLayoutID() {
        return R.layout.module_express_fragment_unclaimed_package;
    }

    private void loadExpressData() {
        new GetExpressListTask(getActivity(), new ITaskCallbackListener() {
            @Override
            public void doTaskComplete(Object o) {
                expressInfoBeans = (List<ExpressInfoBean>) o;
                setData(expressInfoBeans);
            }
        }).execute(expressType + "", (page - 1) * rows + "");
    }

    private void bindExpressAdapter() {
        LinearLayoutManager main_layoutManager = new LinearLayoutManager(getActivity(), LinearLayoutManager.VERTICAL, false);
        unclaimedPackageRv.setHasFixedSize(true);
        unclaimedPackageRv.setFocusable(false);
        unclaimedPackageRv.setLayoutManager(main_layoutManager);
        unclaimedPackageRefresh.setOnRefreshListener(this);
        expressInfoListAdapter = new ExpressInfoListAdapter(R.layout.module_express_item_express_info_list, new ArrayList<>(), expressType);
        expressInfoListAdapter.setOnLoadMoreListener(this, unclaimedPackageRv);
        unclaimedPackageRv.setAdapter(expressInfoListAdapter);
        expressInfoListAdapter.setOnItemChildClickListener(new BaseQuickAdapter.OnItemChildClickListener() {
            @Override
            public void onItemChildClick(BaseQuickAdapter adapter, View view, int position) {
                if (view.getId() == R.id.tv_express_commit_sign) {
                    if (expressType == 0) {
                        showExpressDialog(expressInfoListAdapter.getData().get(position).getId());
                    }
                }
            }
        });
        expressInfoListAdapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
                if (expressInfoListAdapter.getData().get(position) != null && !RxDataTool.isNullString(expressInfoListAdapter.getData().get(position).getCode())) {
                    String[] type = getActivity().getResources().getStringArray(R.array.express_info);
                    String session = BaseSpUtils.getInstance().getAccess_token(getActivity());
                    String url = getActivity().getResources().getString(R.string.express_info_url, expressInfoListAdapter.getData().get(position).getId(), session, type[expressType]);
                    Intent intent = new Intent(getActivity(), PackageDetailActivity.class);
                    intent.putExtra("data", expressInfoListAdapter.getData().get(position));
                    intent.putExtra("url", url);
                    startActivity(intent);
                }
            }
        });
    }

    private void showExpressDialog(String id) {
        AlertDialog alertDialog= new android.app.AlertDialog.Builder(getActivity())
                .setTitle("温馨提醒?")
                .setMessage("请仔细核对信息后再确认收货,确认收货后将不再显示提货码")
                .setNegativeButton("签收", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        expressSignTask(id);
                    }
                })
                .setPositiveButton("取消", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.dismiss();
                    }
                })
                .show();
        alertDialog.getButton(DialogInterface.BUTTON_POSITIVE).setTextColor(Color.RED);
        alertDialog.getButton(DialogInterface.BUTTON_NEGATIVE).setTextColor(Color.BLACK);
    }

    private void setData(List data) {
        if (page == 1) {
            expressInfoListAdapter.setNewData(data);
            unclaimedPackageRefresh.finishRefresh();
        } else {
            expressInfoListAdapter.addData(data);
            expressInfoListAdapter.loadMoreComplete();
        }
    }

    @Override
    protected BaseMvpPresenter createPresenter() {
        return null;
    }

    @Override
    public void onRefresh(RefreshLayout refreshLayout) {
        expressInfoListAdapter.setEnableLoadMore(false);
        page = 1;
        loadExpressData();
        expressInfoListAdapter.setEnableLoadMore(true);
    }

    /**
     * 快递签状态
     *
     * @param id
     */
    private void expressSignTask(String id) {
        new GetExpressSignTask(getActivity(), new ITaskCallbackListener() {
            @Override
            public void doTaskComplete(Object o) {
                BaseEntity baseEntity = (BaseEntity) o;
                if (baseEntity.getRe_code() == 0) {
                    WpToast.l(getActivity(), "签收成功!");
                } else {
                    WpToast.l(getActivity(), "您已签收过该订单!");
                }
            }
        }).execute(id);
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
    }
}
